package org.kjtc.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.kjtc.entity.Page;
import org.kjtc.entity.User;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.stereotype.Service;

@Service("userService")
public class UserService extends BaseService {

	public User getUser(User user) throws Exception{
		return (User)this.getDaoSupport().findForObject("T_User.getUser", user);
	}
	public User getUserPage(User user, Page page) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
    	map.put("info", user);
		map.put("page", page);
		return (User)this.getDaoSupport().findForObject("T_User.getUserPage", user);
	}
	public int saveUser(User user) throws Exception{
		Date now = new Date();
		MessageDigestPasswordEncoder mdpe = new MessageDigestPasswordEncoder("MD5");
		user.setPassword(mdpe.encodePassword(user.getPassword(), now));
		user.setCreateDTTM(now);
		user.setUpdateDTTM(now);
		now = null;
		return (int)this.getDaoSupport().save("T_User.saveUser", user);
	}
	public int updateUser(User user) throws Exception{
		return (int)this.getDaoSupport().update("T_User.updateUser", user);
	}
	public int updatePassword(User user) throws Exception{
		User hssyUser = new User();
		hssyUser.setUserID(user.getUserID());
		User resultUser = getUser(hssyUser);
		hssyUser = null;
		if (resultUser != null) {
			Date now = new Date();
			MessageDigestPasswordEncoder mdpe = new MessageDigestPasswordEncoder("MD5");
			if (user.getOldPassword() != null && !user.getOldPassword().isEmpty()) {
				user.setOldPassword(mdpe.encodePassword(user.getOldPassword(), resultUser.getUpdateDTTM()));
			}
			user.setPassword(mdpe.encodePassword(user.getPassword(), now));
			user.setUpdateDTTM(now);
			now = null;
			resultUser = null;
			return (int)this.getDaoSupport().update("T_User.updatePassword", user);
		} else {
			resultUser = null;
			return 0;
		}

	}
	public int deleteUser(User user) throws Exception{
		return (int)this.getDaoSupport().delete("T_User.deleteUser", user);
	}
}
